package cn.tannn.captcha.sdk.util;

import cn.hutool.captcha.*;
import cn.tannn.captcha.sdk.config.CaptchaFontConfig;
import cn.tannn.captcha.sdk.config.CaptchaSetting;

import java.awt.*;

/**
 * 验证码字体优化工具类
 *
 * @author tan
 * @version V1.0
 * @date 2025/1/6
 */
public class CaptchaFontUtil {

    private final CaptchaSetting captchaSetting;

    public CaptchaFontUtil(CaptchaSetting captchaSetting) {
        this.captchaSetting = captchaSetting;
    }

    private  Font createFont(String preferredFontName, int fontSize) {
        // Font.BOLD = 1 (粗体)
        // 尝试创建首选字体
        Font font = new Font(preferredFontName, Font.BOLD, fontSize);

        // 检查字体是否可用,如果不可用则使用系统字体
        if (!font.getFamily().equalsIgnoreCase(preferredFontName)) {
            font = new Font(Font.SANS_SERIF, Font.BOLD, fontSize);
        }

        return font;
    }


    /**
     * 创建带优化字体的线条验证码
     */
    public  LineCaptcha createOptimizedLineCaptcha(int width, int height, int codeCount, int lineCount) {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(width, height, codeCount, lineCount);
        setCharFont(captcha);
        return captcha;
    }

    /**
     * 创建带优化字体的圆圈验证码
     */
    public  CircleCaptcha createOptimizedCircleCaptcha(int width, int height, int codeCount, int circleCount) {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, circleCount);
        setCharFont(captcha);
        return captcha;
    }

    /**
     * 创建带数学字体优化的扭曲验证码
     */
    public  ShearCaptcha createMathShearCaptcha(int width, int height, int codeCount, int thickness) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(width, height, codeCount, thickness);
        setMathFont(captcha);
        return captcha;
    }

    /**
     * 创建带字符字体优化的扭曲验证码
     */
    public  ShearCaptcha createCharShearCaptcha(int width, int height, int codeCount, int thickness) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(width, height, codeCount, thickness);
        setCharFont(captcha);
        return captcha;
    }

    /**
     * 为字符/数字验证码设置易识别字体
     */
    private  void setCharFont(AbstractCaptcha captcha) {
        // 使用 Arial 字体，粗体，大小适中 -SANS_SERIF
        CaptchaFontConfig config = captchaSetting.getFont();
        Font font = createFont(
                config.getCharFontName(),
                config.getCharFontSize()
        );
        captcha.setFont(font);
    }

    /**
     * 为数学验证码设置易识别字体
     */
    private  void setMathFont(AbstractCaptcha captcha) {
        // 使用等宽字体，便于数学表达式对齐 - MONOSPACED
        CaptchaFontConfig config = captchaSetting.getFont();
        Font font = createFont(
                config.getMathFontName(),
                config.getMathFontSize()
        );
        captcha.setFont(font);
    }

}
